package com.darkteam.jhades.common;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

import com.darkteam.jhades.common.message.JHadesSerializable;
import com.darkteam.jhades.cs.message.type.Head;


@ChannelPipelineCoverage("all")
public class BaseServerEncoder extends OneToOneEncoder {

	private static final Logger logger = Logger.getLogger(BaseServerEncoder.class.getName());
	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel,
			Object msg) throws Exception {
		
		JHadesSerializable hadesSerializable = (JHadesSerializable)msg; 
		
		
		ChannelBuffer message = hadesSerializable.toChannelBuffer();
		ChannelBuffer buf;
		
		int messageSize = message.readableBytes();
		int pacoteSize = messageSize;
		if(messageSize < 3){
			pacoteSize += 2;// HH SS XX*
			buf = ChannelBuffers.buffer(pacoteSize);
			buf.writeByte(Head.C1.getType());
			buf.writeByte((byte) pacoteSize);			
		}else{
			pacoteSize += 3;// HH SS SS XX*
			buf = ChannelBuffers.buffer(pacoteSize);
			buf.writeByte(Head.C2.getType());
			buf.writeShort((short)pacoteSize);
		}	
		
		buf.writeBytes(message);
		logger.log(Level.INFO, ("encode: " + ChannelBuffers.hexDump(buf)));
		return buf;
	}

}
